<?php
namespace App\Service\Admin\Platform;

use Illuminate\Support\Facades\DB;

class AccountService extends BaseService
{
    //账户

    /**
     * 个人用户列表
     * @param array $pas 【uname】
     * @param array $pages【start，limit】
     */
    public function getUserIndex($pas, $pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbUser)->where('del', 0)
            ->where('role_type', 1)
            ->where('cid', 0);
        if (isset($pas['uname']) && $pas['uname']) {
            $db = $db->where('realname', 'like', $pas['uname'].'%');
        }
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return $this->toback(-2, '没有记录');
        }
        $dbTypes = $this->userDbTypes;
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            //有效天数
            $days = ceil((strtotime($v['end_time']) - strtotime($v['start_time'])) / 3600 / 24);
            //数据库类型
            $dbStr = array_key_exists($v['db_type'], $dbTypes) ? $dbTypes[$v['db_type']] : '';
            //前端语言
            $langFront = $this->dbConn($this->dbMkConfig)
                ->where('id', $v['lang_front'])
                ->value('title');
            //后端语言
            $langBack = $this->dbConn($this->dbMkConfig)
                ->where('id', $v['lang_back'])
                ->value('title');
            $arys[] = [
                'id' => $v['id'],
                'account' => $v['uname'],
                'passwd' => $v['passwd'],
                'realname' => $v['realname'],
                'idcard_front' => $v['idcard_front'],
                'idcard_back' => $v['idcard_back'],
                'phone' => $v['phone'],
                'start_time' => $v['start_time'],
                'end_time' => $v['end_time'],
                'period_day' => $days,
                'lang_front_cn' => $langFront ? $langFront : '',
                'lang_back_cn' => $langBack ? $langBack : '',
                'db_type_cn' => $dbStr,
                'addtime' => $v['addtime'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    /**
     * 企业用户列表
     * @param array $pas 【uname】
     * @param array $pages【start，limit】
     */
    public function getCompanyIndex($pas, $pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbUser)->where('del', 0)
            ->where('role_type', 1)
            ->where('cid', '>', 0);
        if (isset($pas['uname']) && $pas['uname']) {
            $db = $db->where('realname', 'like', $pas['uname'].'%');
        }
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return $this->toback(-2, '没有记录');
        }
        $dbTypes = $this->userDbTypes;
        $imgPrefix = env('DOMAIN').'/';
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            //公司信息
            $comOne = (array) $this->dbConn($this->dbCompany)->where('id', $v['cid'])->first();
            //有效天数
            $days = ceil((strtotime($v['end_time']) - strtotime($v['start_time'])) / 3600 / 24);
            //数据库类型
            $dbStr = array_key_exists($v['db_type'], $dbTypes) ? $dbTypes[$v['db_type']] : '';
            //前端语言
            $langFront = $this->dbConn($this->dbMkConfig)
                ->where('id', $v['lang_front'])
                ->value('title');
            //后端语言
            $langBack = $this->dbConn($this->dbMkConfig)
                ->where('id', $v['lang_back'])
                ->value('title');
            //开户人
            $byUser = (array) $this->dbConn($this->dbUser)->where('id', $v['by_uid'])->value('uname');
            $arys[] = [
                'id' => $v['id'],
                'cname' => empty($comOne) ? '-' : $comOne['cname'],
                'address' => empty($comOne) ? '-' : $comOne['address'],
                'account' => $v['uname'],
                'passwd' => $v['passwd'],
                'realname' => $v['realname'],
                'idcard_front' => file_exists($v['idcard_front']) ? $imgPrefix.$v['idcard_front'] : '',
                'idcard_back' => file_exists($v['idcard_back']) ? $imgPrefix.$v['idcard_back'] : '',
                'yyzz' => !empty($comOne)&&file_exists($comOne['yyzz']) ? $imgPrefix.$comOne['yyzz'] : '',
                'phone' => $v['phone'],
                'start_time' => $v['start_time'],
                'end_time' => $v['end_time'],
                'period_day' => $days,
                'user_limit' => $v['user_limit'],
                'total' => $v['user_total'] + $v['company_total'] + $v['agent_total'],
                'lang_front_cn' => $langFront ? $langFront : '-',
                'lang_back_cn' => $langBack ? $langBack : '-',
                'db_type_cn' => $dbStr,
                'addtime' => $v['addtime'],
                'by_user' => $byUser ? $byUser : '-',
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    /**
     * 代理商列表
     * @param array $pas 【uname】
     * @param array $pages【start，limit】
     */
    public function getAgentIndex($pas, $pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbUser)->where('del', 0)
            ->where('role_type', 2);
        if (isset($pas['uname']) && $pas['uname']) {
            $db = $db->where('realname', 'like', $pas['uname'].'%');
        }
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return $this->toback(-2, '没有记录');
        }
        $imgPrefix = env('DOMAIN').'/';
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            //公司信息
            $comOne = (array) $this->dbConn($this->dbCompany)->where('id', $v['cid'])->first();
            //有效天数
            $days = ceil((strtotime($v['end_time']) - strtotime($v['start_time'])) / 3600 / 24);
            //开户人
            $byUser = (array) $this->dbConn($this->dbUser)->where('id', $v['by_uid'])->value('uname');
            $arys[] = [
                'id' => $v['id'],
                'cname' => empty($comOne) ? '-' : $comOne['cname'],
                'address' => empty($comOne) ? '-' : $comOne['address'],
                'account' => $v['uname'],
                'passwd' => $v['passwd'],
                'realname' => $v['realname'],
                'idcard_front' => file_exists($v['idcard_front']) ? $imgPrefix.$v['idcard_front'] : '',
                'idcard_back' => file_exists($v['idcard_back']) ? $imgPrefix.$v['idcard_back'] : '',
                'yyzz' => !empty($comOne)&&file_exists($comOne['yyzz']) ? $imgPrefix.$comOne['yyzz'] : '',
                'phone' => $v['phone'],
                'company_total' => $v['company_total'],
                'user_total' => $v['user_total'],
                'start_time' => $v['start_time'],
                'end_time' => $v['end_time'],
                'period_day' => $days,
                'addtime' => $v['addtime'],
                'by_user' => $byUser ? $byUser : '-',
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    //选项
    public function getOption()
    {
        //前端语言，后端语言，用户角色类型，用户主体类型
        $arys = ['front' => [], 'back' => [], 'db_type' => [], 'role_type' => [], 'body_type' => []];
        //前端语言
        $arys['front'] = $this->dbConn($this->dbMkConfig)
            ->select('id', 'title')
            ->where('del', 0)
            ->where('type', 2)
            ->get();
        //后端语言
        $arys['back'] = $this->dbConn($this->dbMkConfig)
            ->select('id', 'title')
            ->where('del', 0)
            ->where('type', 3)
            ->get();
        //数据库类型
        $dbTypes = $this->userDbTypes;
        foreach ($dbTypes as $k => $v) {
            $arys['db_type'][] = [
                'id' => $k,
                'title' => $v,
            ];
        }
        //用户角色类型
        $roleTypes = $this->userRoleTypes;
        foreach ($roleTypes as $k => $v) {
            $arys['role_type'][] = [
                'id' => $k,
                'title' => $v,
            ];
        }
        //用户主体类型
        $bodyTypes = $this->userBodyTypes;
        foreach ($bodyTypes as $k => $v) {
            $arys['body_type'][] = [
                'id' => $k,
                'title' => $v,
            ];
        }
        return $arys;
    }

    //上传图片
    public function upload($uid, $fpath)
    {
        return $this->dbConn($this->dbImage)->insertGetId([
            'uid' => $uid, 'link' => $fpath, 'addtime' => toDate(),
        ]);
    }

    /**
     * 账号添加
     * @param array $pas 个人信息
     * @param array $gs 公司信息
     */
    public function addUser($pas, $gs)
    {
        $db = $this->dbConn($this->dbUser)->where('del', 0);
        $res = (array) $db->where('realname', $pas['realname'])->first();
        if (!empty($res)) {
            return $this->toback(-2, '已存在同姓名账号');
        }
        $res = (array) $db->where('uname', $pas['uname'])->first();
        if (!empty($res)) {
            return $this->toback(-2, '已存在同名账号');
        }
        $res = (array) $db->where('phone', $pas['phone'])->first();
        if (!empty($res)) {
            return $this->toback(-2, '已存在同手机号账号');
        }
        //公司信息
        $cid = 0;
        if ($gs['cname']) {
            $comOne = (array) $this->dbConn($this->dbCompany)
                ->where('cname', $gs['cname'])
                ->first();
            if (empty($comOne)) {
                $cid = $this->dbConn($this->dbCompany)->insertGetId([
                    'cname' => $gs['cname'], 'addtime' => toDate(), 'uptime' => toDate(),
                ]);
                if (!$cid) {
                    return $this->toback(-1, '公司添加失败');
                }
            } else {
                $cid = $comOne['id'];
            }
        }
        //个人信息
        $pas['addtime'] = toDate();
        $pas['uptime'] = toDate();
        $pas['passwd'] = md5($pas['passwd']);
        $pas['cid'] = $cid;
        $lastid = $this->dbConn($this->dbUser)->insertGetId($pas);
        if (!$lastid) {
            return $this->toback(-1, '添加失败');
        }
        return $this->toback();
    }

    /**
     * 账号修改
     * @param array $pas 个人信息
     * @param array $gs 公司信息
     */
    public function modifyUser($id, $pas, $gs)
    {
        $res = (array) $this->dbConn($this->dbUser)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '账号不存在');
        }
        $db = $this->dbConn($this->dbUser)
            ->where('del', 0)
            ->where('id', '<>', $id);
        $old = (array) $db->where('realname', $pas['realname'])->first();
        if (!empty($old)) {
            return $this->toback(-2, '已存在同姓名账号');
        }
        $old = (array) $db->where('uname', $pas['uname'])->first();
        if (!empty($old)) {
            return $this->toback(-2, '已存在同名账号');
        }
        $old = (array) $db->where('phone', $pas['phone'])->first();
        if (!empty($old)) {
            return $this->toback(-2, '已存在同手机号账号');
        }
        //公司信息
        $comOne = (array) $this->dbConn($this->dbCompany)
            ->where('id', $res['cid'])
            ->first();
        if (empty($comOne)) {
            $cid = $this->dbConn($this->dbCompany)->insertGetId([
                    'cname' => $gs['cname'], 'addtime' => toDate(), 'uptime' => toDate(),
                ]);
            if (!$cid) {
                return $this->toback(-1, '公司添加失败');
            }
            $pas['cid'] = $cid;
        } else {
            $up = $this->dbConn($this->dbCompany)
                ->where('id', $res['cid'])
                ->update([
                    'cname' => $gs['cname'], 'uptime' => toDate(),
                ]);
            if (!$up) {
                return $this->toback(-1, '公司修改失败');
            }
        }
        //个人信息
        $pas['uptime'] = toDate();
        $pas['passwd'] = md5($pas['passwd']);
        $lastid = $this->dbConn($this->dbUser)->where('id', $id)->update($pas);
        if (!$lastid) {
            return $this->toback(-1, '添加失败');
        }
        return $this->toback();
    }

    /**
     * 代理商添加
     * @param array $pas 个人信息
     * @param array $gs 公司信息
     */
    public function addAgent($pas, $gs)
    {
        $db = $this->dbConn($this->dbUser)->where('del', 0);
        $res = (array) $db->where('realname', $pas['realname'])->first();
        if (!empty($res)) {
            return $this->toback(-2, '已存在同姓名账号');
        }
        $res = (array) $db->where('uname', $pas['uname'])->first();
        if (!empty($res)) {
            return $this->toback(-2, '已存在同名账号');
        }
        $res = (array) $db->where('phone', $pas['phone'])->first();
        if (!empty($res)) {
            return $this->toback(-2, '已存在同手机号账号');
        }
        //公司信息
        $comOne = (array) $this->dbConn($this->dbCompany)
            ->where('cname', $gs['cname'])
            ->first();
        if (empty($comOne)) {
            $cid = $this->dbConn($this->dbCompany)->insertGetId([
                'cname' => $gs['cname'], 'addtime' => toDate(), 'uptime' => toDate(),
            ]);
            if (!$cid) {
                return $this->toback(-1, '公司添加失败');
            }
        } else {
            $cid = $comOne['id'];
        }
        //个人信息
        $pas['cid'] = $cid;
        $pas['addtime'] = toDate();
        $pas['uptime'] = toDate();
        $pas['passwd'] = md5($pas['passwd']);
        $lastid = $this->dbConn($this->dbUser)->insertGetId($pas);
        if (!$lastid) {
            return $this->toback(-1, '添加失败');
        }
        return $this->toback();
    }

    /**
     * 代理商修改
     * @param array $pas 个人信息
     * @param array $gs 公司信息
     */
    public function modifyAgent($id, $pas, $gs)
    {
        $res = (array) $this->dbConn($this->dbUser)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '账号不存在');
        }
        $db = $this->dbConn($this->dbUser)
            ->where('del', 0)
            ->where('id', '<>', $id);
        $old = (array) $db->where('realname', $pas['realname'])->first();
        if (!empty($old)) {
            return $this->toback(-2, '已存在同姓名账号');
        }
        $old = (array) $db->where('uname', $pas['uname'])->first();
        if (!empty($old)) {
            return $this->toback(-2, '已存在同名账号');
        }
        $old = (array) $db->where('phone', $pas['phone'])->first();
        if (!empty($old)) {
            return $this->toback(-2, '已存在同手机号账号');
        }
        //公司信息
        $comOne = (array) $this->dbConn($this->dbCompany)
            ->where('id', $res['cid'])
            ->first();
        if (empty($comOne)) {
            return $this->toback(-2, '没有公司记录');
        }
        $up = $this->dbConn($this->dbCompany)
            ->where('id', $res['cid'])
            ->update([
                'cname' => $gs['cname'], 'uptime' => toDate(),
            ]);
        if (!$up) {
            return $this->toback(-1, '公司修改失败');
        }
        //个人信息
        $pas['uptime'] = toDate();
        $pas['passwd'] = md5($pas['passwd']);
        $lastid = $this->dbConn($this->dbUser)->where('id', $id)->update($pas);
        if (!$lastid) {
            return $this->toback(-1, '添加失败');
        }
        return $this->toback();
    }

    /**
     * 禁用启用
     * @param int $id 用户ID
     * @param int $enable 1禁用，2启用
     */
    public function setEnable($id, $enable)
    {
        $res = (array) $this->dbConn($this->dbUser)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '记录不存在');
        }
        if ($res['is_enable'] == $enable) {
            return $this->toback(-2, '已是该状态');
        }
        $up = $this->dbConn($this->dbUser)->where('id', $id)->update([
            'is_enable' => $enable, 'en_time' => toDate(),
        ]);
        if (!$up) {
            return $this->toback(-1, '更新状态失败');
        }
        return $this->toback();
    }

    /**
     * 删除
     * @param string $ids ID数组
     */
    public function setDel($ids)
    {
        $total = $this->dbConn($this->dbUser)
            ->where('del', 0)
            ->whereIn('id', $ids)
            ->count('id');
        if (!$total) {
            return $this->toback(-2, '没有记录');
        }
        $up = $this->dbConn($this->dbUser)->whereIn('id', $ids)->update([
            'del' => 1, 'deltime' => toDate(),
        ]);
        if (!$up) {
            return $this->toback(-1, '删除失败');
        }
        return $this->toback();
    }
}